package com.eqxiu.ieditor.weixin.event;

import com.eqxiu.user.api.dto.RelAccount;
import com.eqxiu.user.api.dto.UserExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component
public class UnsubscribeEventListenner extends AbstractEventListenner{

	private Logger logger = LoggerFactory.getLogger(getClass());

	@EventListener
	@Async
    @Transactional(rollbackFor = Exception.class)
	public void handleEvent(UnsubscribeEvent event) {
	    try{
	        String wechatName = event.getToUserName();
            if(!super.weChatName.equals(wechatName)){
                return;
            }

            String openId = event.getOpenId() ;
            String unionid = getUnionId(openId);
            if(unionid != null){
                RelAccount relAccount = getRelAccount(unionid);
                if(relAccount != null){
                    String userId = relAccount.getRelUser();
                    saveUserFlag(userId);
                }
            }
        }catch (Exception e){
	        logger.error(e.getMessage(),e);
        }
	}


    /**
     * 保存用户扩展数据
     * @param userId
     */
    public void saveUserFlag(String userId){
        UserExt userExt = userApi.getUserExt(userId);
        userExt.getPropertyMap().put(WECHAT_FOLLOWED,false);
        userExt.refreshProperty();
        userApi.saveOrUpdateUserExt(userExt);
    }



}
